//
//  CollectViewController.m
//  FloatClouds
//
//  Created by 黄威 on 16/9/19.
//  Copyright © 2016年 黄威. All rights reserved.
//

#import "CollectViewController.h"
#import "CollectCell.h"
#import "HotModel.h"
#import <sqlite3.h>
#import "FMDB.h"
#import "CollectData.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "ProductDetailTableViewController.h"
@interface CollectViewController ()
@property (nonatomic, retain) HotModel *hotmodel;
@property (nonatomic, retain) FMDatabase *db;
@property (nonatomic, retain) NSMutableArray *arrayOfCollectData;
@property (nonatomic, strong) NSMutableArray<NSIndexPath *> *selectedIndexArray;
@property (nonatomic, strong) NSMutableArray<NSString *> *selectedNameArray;
@property (nonatomic, copy) NSString *DeleteSQLSTR;
@end


@implementation CollectViewController


- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil];
    
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    self.navigationItem.title = @"我的收藏";
    
    
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editAction)];
    
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
  //  self.tableView.allowsMultipleSelectionDuringEditing = YES;
  
   
}

    
    


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
   
    
    self.arrayOfCollectData = [NSMutableArray array];
    
   
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self handleData];
        
        [self.tableView.mj_header endRefreshing];
    }];

    
    [self.tableView registerClass:[CollectCell class] forCellReuseIdentifier:@"CollectCell"];

    self.selectedIndexArray = [NSMutableArray array];
    self.selectedNameArray = [NSMutableArray array];
  
    [self handleData];

}


- (void)handleData{

    [self.arrayOfCollectData removeAllObjects];
    
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
 
    NSString *sqlFilePath = [documentPath stringByAppendingPathComponent:@"cigarette.sqlite"];
    
    self.db = [FMDatabase databaseWithPath:sqlFilePath];
    if ([self.db open]) {
        NSLog(@"打开成功");
        
    } else {
        NSLog(@"打开失败");
    }
    
    
    FMResultSet *result = [self.db executeQuery:@"SELECT * FROM cigaretteCollect"];
    
    
    
    while ([result next]) {
        
        CollectData *collectData = [[CollectData alloc]init];
        
        // NSInteger ID = [result intForColumnIndex:0];
        collectData.name = [result stringForColumn:@"name"];
        collectData.score = [result stringForColumn:@"score"];
        collectData.price = [result stringForColumn:@"price"];
        collectData.productID = [result stringForColumn:@"productID"];
        collectData.photo = [result stringForColumn:@"photo"];
        
        
        [self.arrayOfCollectData addObject:collectData];
        
        
    }
    
    
    [self.tableView reloadData];

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    CollectData *collectData = self.arrayOfCollectData[indexPath.row];
    
    CollectCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"CollectCell"];
  
    NSURL *url = [NSURL URLWithString:collectData.photo];
    [cell.imageViewLift sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder"]];
    cell.name.text = collectData.name;
    cell.priceinput.text = collectData.price;
    cell.catrameinput.text = collectData.score;
    cell.productID = collectData.productID;
    cell.selectionStyle = UITableViewCellSelectionStyleGray;

    return cell;
  
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.arrayOfCollectData.count;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 95;


}
- (void)viewDidDisappear:(BOOL)animated{

    [super viewDidDisappear:animated];

    [self.db close];
}





-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

   

    // 在全选状态下,数组中添加对应选中的下标
    if (self.editing) {
        
        
        
        CollectCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        
        
        NSString *name = cell.name.text;
        
        [_selectedIndexArray addObject:indexPath];
        [_selectedNameArray addObject:name];
        
    }
    
    
    if (!self.editing) {
        
        
        ProductDetailTableViewController *product = [[ProductDetailTableViewController alloc]init];
        
        CollectCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        
        product.productId = cell.productID;
        
        [self.navigationController pushViewController:product animated:YES];
    }
   


}


- (void)editAction {
    
    [self.navigationItem.rightBarButtonItem setTitle:@"删除"];
    
    [self performSelector:NSSelectorFromString(@"_toggleEditing:")];
    
    
    
    if (self.editing == NO) {
        
        self.DeleteSQLSTR = @"DELETE FROM cigaretteCollect WHERE ";
        
        
        for (int i = 0; i < self.selectedNameArray.count; i++) {
            
            
            NSString *str = [NSString stringWithFormat:@" name = '%@' or ",self.selectedNameArray[i]];
            
            if (i == self.selectedNameArray.count - 1)
            {
                
               str = [NSString stringWithFormat:@" name = '%@' ",self.selectedNameArray[i]];

            
            }
          self.DeleteSQLSTR = [self.DeleteSQLSTR stringByAppendingString:str];
            
        
        }
        
    BOOL success = [self.db executeUpdate:self.DeleteSQLSTR];
        
        if (success) {
            NSLog(@"删除数据成功");
            
            [self handleData];
            
            [self.navigationItem.rightBarButtonItem setTitle:@"编辑"];

            
        }else{
            NSLog(@"删除数据失败");
        
        }
        
    }
}

#pragma mark delegate
//4.返回cell的编辑状态(样式)
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
   
     return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}


// 取消
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.editing) {
        // 在全选状态下,数组中移除对应选中的下标
        [_selectedNameArray removeObject:self.arrayOfCollectData[indexPath.row]];
        [_selectedIndexArray removeObject:indexPath];
    }
}

#pragma mark - UIViewController
// 2.让tableView处于编辑状态
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
//    if (editing) {
//    } else {
//        // 要删除选中的数组
//        
////            [self.arrayOfCollectData removeObjectsInArray:_selectedNameArray];
////            [self.tableView deleteRowsAtIndexPaths:_selectedIndexArray withRowAnimation:UITableViewRowAnimationLeft];
////                [_selectedIndexArray removeAllObjects];
////                [_selectedNameArray removeAllObjects];
//    }
}
#pragma mark datasource
// 3.控制tableView能否编辑 NO 不能编辑 YES 能编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}


@end
